<template>
  <el-amap
    ref="map"
    map-style="amap://styles/62009be025f187dd3eafe327d2e55b8e"
    :center="center"
    :zoom="zoom"
    view-mode="2D"
    class="amap-demo"
    style="height: 100%"
    @init="initMap"
    @click="clickMap"
  >
    <el-amap-control-geolocation @complete="getLocation" />
    <el-amap-control-scale />
    <el-amap-control-tool-bar />

    <el-amap-marker
      v-for="(marker, index) in markers"
      :key="index"
      :position="marker.position"
      @click="
        (e) => {
          handleMarkerClick(marker, e);
        }
      "
    />

    <el-amap-info-window
      v-if="currentInfo"
      :position="currentInfo.pos"
      :visible="currentInfo.visible"
      is-custom
      close-when-click-map
    >
      <el-card class="box-card">
        <el-descriptions title="详细信息" :column="1" border size="mini">
          <el-descriptions-item label="上传时间">{{
            currentInfo.time
          }}</el-descriptions-item>
          <el-descriptions-item label="上传地点">{{
            currentInfo.address
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-amap-info-window>
  </el-amap>
</template>

<script>
import { listPosAll } from "@/api/event/pos";

export default {
  name: "UserPos",
  props: {
    userId: {
      type: String,
    },
  },
  data() {
    return {
      zoom: 12,
      center: [112.551315, 37.864679],
      mapObj: null,
      markers: [],
      currentInfo: undefined,
    };
  },
  watch: {
    userId: {
      handler() {
        this.loadUserPos();
      },
    },
  },
  mounted() {
    this.loadUserPos();
  },
  methods: {
    refresh() {
      this.loadUserPos();
    },
    handleMarkerClick(marker, event) {
      this.currentInfo = {
        pos: [event.lnglat.lng, event.lnglat.lat],
        visible: true,
        time: marker.createTime,
        address: marker.address,
      };
    },
    loadUserPos() {
      this.markers = [];
      listPosAll({ userId: this.userId }).then((res) => {
        this.markers = res.data.map((d) => {
          return {
            position: [d.lng, d.lat],
            id: d.id,
            ...d,
          };
        });
      });
    },
    getLocation(e) {
      console.log(e);
    },
    getMap() {
      console.log(this.$refs.map.$$getInstance());
    },
    clickMap(e) {
      console.log("click map :", e);
    },
    initMap(e) {
      this.mapObj = e;
      console.log(window.AMap);
    },
  },
};
</script>

<style scoped></style>
